import { HttpException, HttpStatus } from "@nestjs/common";
import { Min } from "class-validator";
import { Client } from "src/modules/client/client.entity";
import { Company } from "src/modules/company/company.entity";
import { DeliveryItem } from "src/modules/delivery-item/delivery-item.entity";
import { Quality } from "src/modules/quality/quality.entity";
import { Type } from "src/modules/type/type.entity";
import { User } from "src/modules/user/user.entity";
import { CustomizeStatus } from "src/utils/status";
import {
  Column,
  CreateDateColumn,
  Entity,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from "typeorm";

@Entity()
export class Order {
  @PrimaryGeneratedColumn("uuid")
  id: string;

  @ManyToOne(() => User, (user) => user.orders, { nullable: false })
  user: User;

  @ManyToOne(() => Company, (company) => company.orders, { nullable: false })
  company: Company;

  @ManyToOne(() => Client, (client) => client.orders, {
    nullable: false,
  })
  client: Client;

  @CreateDateColumn()
  date: Date;

  @UpdateDateColumn()
  update: Date;

  // 客户PO
  @Column({ default: "" })
  po: string;

  // 客方货号
  @Column({ default: "" })
  no: string;

  // 备注
  @Column({ default: "" })
  remark: string;

  @ManyToOne(() => Type, (type) => type.orders, { nullable: false })
  type: Type;

  @ManyToOne(() => Quality, (quality) => quality.orders, { nullable: false })
  quality: Quality;

  @Column({ default: "" })
  size: string;

  @Column({ default: "0" })
  price: string;

  @Column("int", {
    default: 1,
  })
  @Min(1)
  quantity: number;

  /** 未出货的订单 */
  @Column("int")
  @Min(0)
  left: number;

  @OneToMany(() => DeliveryItem, (deliveryItem) => deliveryItem.order)
  deliveryItems: DeliveryItem[];

  @Column({ default: false })
  ifDone: boolean;

  @Column({ nullable: true })
  doneDate: Date;

  set newQuantity(value: number) {
    if (this.ifDone) {
      throw new HttpException(
        {
          message: "商品流程已结束, 被锁定",
          target: "done",
          statusCode: CustomizeStatus.PRECONDITION_NEEDED,
        },
        HttpStatus.FORBIDDEN
      );
    }
    const diff = value - this.quantity;
    this.quantity = value;
    this.newLeft = this.left + diff;
    if (this.quantity < 1) {
      throw new HttpException(
        {
          message: "数量不足",
          target: this,
          statusCode: CustomizeStatus.LACKING,
        },
        HttpStatus.FORBIDDEN
      );
    }
  }

  set newLeft(value: number) {
    this.left = value;
    if (this.ifDone) {
      throw new HttpException(
        {
          message: "商品流程已结束, 被锁定",
          target: this,
          statusCode: CustomizeStatus.PRECONDITION_NEEDED,
        },
        HttpStatus.FORBIDDEN
      );
    }
    if (this.left < 0) {
      throw new HttpException(
        {
          message: "数量不足",
          target: this,
          statusCode: CustomizeStatus.LACKING,
        },
        HttpStatus.FORBIDDEN
      );
    }
  }
}
